package com.itheima.article.job;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.model.common.mess.app.AggBehaviorDTO;
import com.heima.model.common.mess.app.NewBehaviorDTO;
import com.itheima.article.service.HotArticleService;
import com.itheima.common.constants.article.HotArticleConstants;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.support.collections.DefaultRedisList;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class UpdateHotArticleJob {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    HotArticleService hotArticleService;
    @XxlJob("updateHotArticleJob")
    public ReturnT updateHotArticleHandler(String params){
        log.info("热文章分值更新 调度任务开始执行....");
        // TODO 定时更新文章热度
        // 1. 获取redis 行为列表中待处理数据
        List<NewBehaviorDTO> behaviorList = getRedisBehaviorList();
        if (CollectionUtils.isEmpty(behaviorList)) {
            log.info("热文章分值更新: 太冷清了 未产生任何文章行为 调度任务完成....");
            return ReturnT.SUCCESS;
        }
        // 2. 将数据按照文章分组  进行聚合统计 得到待更新的数据列表
        List<AggBehaviorDTO> aggBehaviorList = getAggBehaviorList(behaviorList);
        if (CollectionUtils.isEmpty(aggBehaviorList)) {
            log.info("热文章分值更新: 太冷清了 未产生任何文章行为 调度任务完成....");
            return ReturnT.SUCCESS;
        }

        // 3. TODO 更新数据库文章分值

        log.info("热文章分值更新 调度任务完成....");
        return ReturnT.SUCCESS;
    }

    private List<AggBehaviorDTO> getAggBehaviorList(List<NewBehaviorDTO> behaviorList) {
        List<AggBehaviorDTO> aggBehaviorList = new ArrayList<>();
        //1 按照文章id分组，获取对应分组下的文章列表
        Map<Long, List<NewBehaviorDTO>> listMap = behaviorList.stream().collect(Collectors.groupingBy(NewBehaviorDTO::getArticleId));
        //计算每个分组的结果
        listMap.forEach((articleId,messList)->{
            Optional<AggBehaviorDTO> reduce = messList.stream().map(behavior -> {
                AggBehaviorDTO aggBehavior = new AggBehaviorDTO();
                aggBehavior.setArticleId(articleId);
                switch (behavior.getType()) {
                    case LIKES:
                        // 设置 点赞数量
                        aggBehavior.setLike(behavior.getAdd());
                        break;
                    case VIEWS:
                        // 设置 阅读数量
                        aggBehavior.setView(behavior.getAdd());
                        break;
                    case COMMENT:
                        // 设置 评论数量
                        aggBehavior.setComment(behavior.getAdd());
                        break;
                    case COLLECTION:
                        // 设置 收藏数量
                        aggBehavior.setCollect(behavior.getAdd());
                        break;
                    default:
                }
                return aggBehavior;
            }).reduce((a1, a2) -> {
                a1.setLike(a1.getLike() + a2.getLike());
                a1.setView(a1.getView() + a2.getView());
                a1.setComment(a1.getComment() + a2.getComment());
                a1.setCollect(a1.getCollect() + a2.getCollect());
                return a1;
            });
            if (reduce.isPresent()) {
                // 聚合结果
                AggBehaviorDTO aggBehavior = reduce.get();
                log.info("热点文章 聚合计算结果  ===>{}", aggBehavior);
                aggBehaviorList.add(aggBehavior);
            }

        });
        return aggBehaviorList;
    }

    private List<NewBehaviorDTO> getRedisBehaviorList() {
        //调用脚本
        DefaultRedisScript<List> redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(List.class);
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("redis.lua")));
        //执行脚本
        List<String> result = redisTemplate.execute(redisScript, Arrays.asList(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_LIST) );
        //解析的到NewBehaviorDto对象
        return result.stream().map(jsonstr-> JSON.parseObject(jsonstr,NewBehaviorDTO.class)).collect(Collectors.toList());


    }
}